package rad.framework.trace;

import java.io.Serializable;

import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

import rad.framework.jpa.JpaUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TraceCallbackListener {

	@PrePersist
	public void doPrePersist(Object entity) {
		log("doPrePersist:\n", entity);
	}

	@PostPersist
	public void doPostPersist(Object entity) {
		log("doPostPersist:\n", entity);
	}

	@PreRemove
	public void doPreRemove(Object entity) {
		log("doPreRemove:\n", entity);
	}

	@PostRemove
	public void doPostRemove(Object entity) {
		log("doPostRemove:\n", entity);
	}

	@PreUpdate
	public void doPreUpdate(Object entity) {
		log("doPreUpdate:\n", entity);
	}

	@PostUpdate
	public void doPostUpdate(Object entity) {
		log("doPostUpdate:\n", entity);
	}

	@PostLoad
	public void doPostLoad(Object entity) {
		Log logger = LogFactory.getLog(entity.getClass());
		if (logger.isDebugEnabled()) {
			logger.debug("doPostLoad:\n"
					+ JpaUtil.getIdentityAsString((Serializable) entity));
		}
	}

	private void log(String prefix, Object entity) {
		Log logger = LogFactory.getLog(entity.getClass());
		if (logger.isDebugEnabled()) {
			logger.debug(prefix + entity.toString());
		}
	}
}
